package cn.njxzc.examples;

class CubbyHoleDemo {
	private int content;
	private boolean available = false;

	public synchronized int get() {
		while (available == false) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		available = false;
		notifyAll();
		System.out.println("Consumer " + " got: " + content);
		return content;
	}

	public synchronized void put(int value) {
		while (available == true) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		content = value;
		available = true;
		notifyAll();
		System.out.println("Producer " + " put: " + content);
	}
}

class ProducerDemo extends Thread {
	private CubbyHole cubbyhole;

	public ProducerDemo(CubbyHole c) {
		cubbyhole = c;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			cubbyhole.put(i);
			try {
				sleep((int) (Math.random() * 10));
			} catch (InterruptedException e) {
				System.out.println(e);
			}
		}
	}
}

class ConsumerDemo extends Thread {
	private CubbyHole cubbyhole;

	public ConsumerDemo(CubbyHole c) {
		cubbyhole = c;
	}

	public void run() {
		int value = 0;
		for (int i = 0; i < 10; i++) {
			value = cubbyhole.get();
		}
	}
}

public class ThreadDemo {
	public static void main(String[] args) {
		CubbyHole h = new CubbyHole();
		Producer p = new Producer(h);
		Consumer c = new Consumer(h);
		p.start();
		c.start();
	}
}
